import {mutationWithClientMutationId, fromGlobalId} from "graphql-relay";
import {GraphQLID, GraphQLNonNull, GraphQLString, GraphQLBoolean} from "graphql";
import CompanyType from "../../types/CompanyType";
import { Company } from "../../models";

const UpdateCompanyMutation = mutationWithClientMutationId({
  name: 'updateCompany',
  inputFields: {
    id: { type: new GraphQLNonNull(GraphQLID) },
    name: { type: GraphQLString },
    email: { type: GraphQLString },
    phone: { type: GraphQLString },
    city: { type: GraphQLString },
    address: { type: GraphQLString },
    note: { type: GraphQLString },
    status: { type: GraphQLBoolean },
  },
  outputFields: {
    company: {
      type: CompanyType,
      resolve: async ({ localCompanyId }) => await Company.findById(localCompanyId),
    }
  },
  mutateAndGetPayload: async ({ ...company }) => {
    console.log(company)
    const localCompanyId = parseInt(fromGlobalId(company.id).id, 10);
    const oldCompany = await Company.findById(localCompanyId);
    const copyCompany = Object.assign({}, company);
    delete copyCompany.id;
    Object.keys(copyCompany).forEach((tk) => {
      oldCompany.set(tk, copyCompany[tk]);
    });
    await oldCompany.save();
    return { localCompanyId };
  },
});

export default UpdateCompanyMutation;
